namespace CRM_Perf_BenchMark
{
    using System;
    using System.Collections.Generic;
    using Microsoft.VisualStudio.TestTools.WebTesting;
    using System.Net;
    using System.Text;
    using System.Xml;    

    /// <summary>
    /// 1. Start at marketing tab
    /// 2. Select campaigns 
    /// 3. Select new campaign button
    /// 4. Add relevant data (name)
    /// 5. Click Save and close
    /// </summary>

    public class CreateNewCampaign : CrmWebTest
    {
        public void CreateNewCampaign_PreWebTest(object sender, PreWebTestEventArgs e)
		{
            EntityRequest er = new EntityRequest();
            er.Type = EntityNames.Users;
            er.ReturnAs = EntityNames.Users;
            er.ParentID = EntityManager.Instance.OrgId;

            System.Collections.Hashtable userProps = new System.Collections.Hashtable();
            if (e.WebTest.Context.ContainsKey("UserRole"))
            {
                userProps.Add("role", e.WebTest.Context["UserRole"]);
                er.Props = userProps;
            }            
            
            System.Collections.Hashtable Entities = EntityManager.Instance.GetEntities(er);

            user = (CRMEntity)Entities[EntityNames.Users];

            crmServer = user["CrmServer"];
            tokenKey = EntityManager.Instance.ReadTokenKey(user["organizationid"]);

            orgId = new Guid(user["organizationid"]);

            e.WebTest.UserName = user["domainName"];
            e.WebTest.Password = user["userpassword"];            
        }
       
        public void CreateNewCampaign_PostWebTest(object sender, PostWebTestEventArgs e)
        {            
			//Parse the campaign ID to make sure it's an id...
			try
			{
                if (newCampaignId != null)
                {
                    Guid g = EntityManager.Instance.GetOwnerGuid(new Guid(user[EntityIDNames.User]), new Guid(user["OrganizationId"]));
                    EntityManager.Instance.AddEntity(EntityNames.Campaigns,
						g,
                         new string[] { "OwningUser", "CampaignID", "EntityManagerOwningUser" },
                         new string[] { user["systemuserid"], newCampaignId.ToString() , g.ToString()});
                }
			}
			catch (System.FormatException fe)
			{
				System.Diagnostics.Trace.WriteLine("Failed to convert bogus data into Guid. " + fe.ToString());
			}
			finally
			{
				EntityManager.Instance.FreeEntity(user);
			}
        }

		private void NewCampaign_ValidateResponse(object sender, ValidationEventArgs e)
		{
			string ID = null;

			int idIdx = e.Response.BodyString.IndexOf(newIdMarker);
			ID = e.Response.BodyString.Substring(idIdx + (CreateNewCampaign.newIdMarker.Length), 36);
			try
			{
				ID = new Guid(ID).ToString();
			}
			catch (System.FormatException fe)
			{
				System.Diagnostics.Trace.WriteLine("Format exception: " + fe.ToString());
				e.IsValid = false;
				return;
			}
			e.IsValid = true;
		}

        public CreateNewCampaign()
        {
            WebRequest.RegisterPrefix("crm", new crmRequestFactory());
            gridXml = GridXmlHelper.CampaignPageViewRefresh(-1, myCampaignViewId, null);

            this.Proxy = null;            
            PreWebTest += new EventHandler<PreWebTestEventArgs>(CreateNewCampaign_PreWebTest);
            PostWebTest += new EventHandler<PostWebTestEventArgs>(CreateNewCampaign_PostWebTest);
        }

        public override IEnumerator<WebTestRequest> GetRequestEnumerator()
        {
            this.BeginTransaction("NavCampaignHomepage");

            MA_home_camps_aspx hp = new MA_home_camps_aspx(user);
            yield return (hp);

            this.EndTransaction("NavCampaignHomepage");

            this.BeginTransaction("CreateCampaign");

            ma_camps_edit_aspx campPage = new ma_camps_edit_aspx(user);
            yield return (campPage);

            referer = campPage.lastResponse.ResponseUri.AbsoluteUri;

            _forms_FormScript_js_aspx formScript = new _forms_FormScript_js_aspx(user);
            formScript.etc = 4400;
            formScript.FormType = "main";
            formScript.FormName = "crmForm";
            headerItem = new WebTestRequestHeader("referer", referer);
            formScript.Headers.Add(headerItem);
            yield return (formScript);

            campPage = new ma_camps_edit_aspx(user);
            campPage.crmFormSubmitXml = EntityXmlHelper.GetCreateCampaignXml(new Guid(user[EntityIDNames.User]), 8);
            campPage.crmFormSubmitMode = 1;
            campPage.crmFormUserModified = true;
            campPage.crmFormSubmitObjectType = 4400;
            campPage.crmFormSubmitSecurity = 852023;
            campPage.crmFormSubmitOnline = 1;

            rpcInfo = Utils.GenerateWRPCToken(ma_camps_edit_aspx.url, user, tokenKey);
            campPage.CRMWRPCToken = rpcInfo.token;
            campPage.CRMWRPCTokenTimeStamp = rpcInfo.timeStamp;
            campPage.ValidateResponse += this.NewCampaign_ValidateResponse;
            yield return (campPage);

            //get the newly created campaign id out of the post reply
            int idIdx = campPage.lastResponse.BodyString.IndexOf(newIdMarker);
            string tempNewCampaignId = campPage.lastResponse.BodyString.Substring(idIdx + (CreateNewCampaign.newIdMarker.Length), 36);
            newCampaignId = new Guid(tempNewCampaignId);

            AppGridWebService.AppGridWebService agws = new AppGridWebService.AppGridWebService();
            CrmRequest wtrRefresh = null;
            try { agws.Refresh(gridXml); }
            catch (crmException x)
            {
                wtrRefresh = (CrmRequest)x.wtr;
                wtrRefresh.Url = Utils.ReplaceServerName(wtrRefresh.Url, user);

                string urlPath = wtrRefresh.Url.Remove(0, crmServer.Length);
                urlPath = urlPath.Remove(0, user["organizationName"].Length + 1);

                rpcInfo = Utils.GenerateWRPCToken(urlPath, user, tokenKey);

                headerItem = new WebTestRequestHeader();
                headerItem.Name = "crmwrpctokentimestamp";
                headerItem.Value = rpcInfo.timeStamp.ToString();
                wtrRefresh.Headers.Add(headerItem);
                headerItem = new WebTestRequestHeader();
                headerItem.Name = "crmwrpctoken";
                headerItem.Value = rpcInfo.token;
                wtrRefresh.Headers.Add(headerItem);
                wtrRefresh.Method = "Post";
            }
            yield return (wtrRefresh);

            this.EndTransaction("CreateCampaign");
        }

        private const string newIdMarker = @"separator + ""id=";
        private CRMEntity user;
        private Guid newCampaignId;
        private string crmServer;
        private string tokenKey;
        private string gridXml;
        private static string myCampaignViewId = "7F68A34B-26F1-430F-B3EF-7079F2925C69";
        private Guid orgId;
        private string referer;
        private WRPCInfo rpcInfo;
        private WebTestRequestHeader headerItem;
    }
}
